package cn.lkk.samples.lang.thread;

/**
 * 使用三个线程循环打印ABC30次
 */
public class PrintABC {

    static int status = 0;

    public static void main(String[] args) {
        final int count = 5;
        final Object obj = new Object();

        Thread t1 = new Thread() {
            @Override
            public void run() {
                for (int i = 0; i < count; ++i) {
                    synchronized (obj) {
                        while (status % 3 != 0)
                            try {
                                obj.wait();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }

                        System.out.println("-A");
                        ++status;
                        obj.notifyAll();

                    }
                }
            }
        };

        Thread t2 = new Thread() {
            @Override
            public void run() {
                for (int i = 0; i < count; ++i) {
                    synchronized (obj) {
                        while (status%3!=1)
                            try {
                                obj.wait();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }

                        System.out.println("--B");
                        ++status;
                        obj.notifyAll();
                    }
                }
            }
        };

        Thread t3 = new Thread() {
            @Override
            public void run() {
                for (int i = 0; i < count; ++i) {
                    synchronized (obj) {
                        while (status%3!=2)
                            try {
                                obj.wait();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }

                        System.out.println("---C");
                        ++status;
                        obj.notifyAll();
                    }
                }
            }
        };

        t1.start();
        t2.start();
        t3.start();
    }
}
